package com.zzptc.myapp1112;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.zzptc.myapp1112.Bean.Msg;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {
    private ListView chatlv;
    private TextView chattxt;
    private EditText senddeit;
    private Button   sendbtn;
    private int sendid,receiveid;
    private String receivename;

    List<Msg> msgList=new ArrayList<>();
    List<String> dataList=new ArrayList<>();
    ArrayAdapter<String> adapeter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initData();
        initView();
        setListener();


    }

    private void initData() {
        SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
        sendid=sp.getInt("myid",-1);
        receiveid=sp.getInt("friendid",-1);
        receivename=sp.getString("friendname","");
        for (Msg msg:LitePal.findAll(Msg.class)){
            boolean a=sendid== msg.getSend_id()&&receiveid== msg.getReceive_id();
            boolean b =sendid== msg.getReceive_id()&&receiveid== msg.getSend_id();
            if (a||b){
                msgList.add(msg);

            }
        }
        for (Msg m:msgList){
            dataList.add(m.getContent());

        }
    }

    private void setListener() {
        sendbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=senddeit.getText().toString().trim();
                Msg msg=new Msg(0,sendid,receiveid,content,new Date());
                msg.save();
                dataList.add(msg.getContent());
                adapeter.notifyDataSetChanged();


            }
        });


    }

    private void initView() {
        chatlv=findViewById(R.id.contactlv);
        chattxt=findViewById(R.id.chattxt);
        senddeit=findViewById(R.id.senddeit);
        sendbtn=findViewById(R.id.sendbtn);
        chattxt.setText("正在与"+receivename+"聊天中");
        adapeter=new ArrayAdapter<String>(ChatActivity.this,android.R.layout.simple_list_item_1,dataList);
        chatlv.setAdapter(adapeter);
    }
}
